package com.yungu.swift.order.helper.chain;

import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.order.dao.OrderEvaluateMapper;
import com.yungu.swift.order.helper.model.AssignScoreParam;
import com.yungu.swift.order.helper.model.DriverScoreVo;
import com.yungu.swift.utils.ParamUtil;
import org.apache.commons.collections4.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 司机服务分处理器
 *
 * @author : cuixiuyin
 * @date : 2019/7/8
 */
public class DriverScoreHandler extends AssignScoreHandler {

    private OrderEvaluateMapper orderEvaluateMapper;

    public DriverScoreHandler(OrderEvaluateMapper orderEvaluateMapper) {
        this.orderEvaluateMapper = orderEvaluateMapper;
    }

    @Override
    public void calculation(List<AssignScoreParam> scoreParams) {
        if (CollectionUtils.isNotEmpty(scoreParams)) {
            List<String> driverUuids = scoreParams.stream().map(AssignScoreParam::getDriverUuid).collect(Collectors.toList());
            // 统计司机评分
            List<DriverScoreVo> driverScoreVos = orderEvaluateMapper.listDriverScore(driverUuids);
            Map<String, DriverScoreVo> driverScoreVoMap = driverScoreVos.stream().collect(Collectors.toMap(
                    DriverScoreVo::getDriverUuid, driverScoreVo -> driverScoreVo, (oldValue, newValue) -> newValue));
            scoreParams.forEach(scoreParam -> {
                DriverScoreVo driverScoreVo = driverScoreVoMap.get(scoreParam.getDriverUuid());
                scoreParam.setScore(scoreParam.getScore() + score(driverScoreVo));
            });
        }
        if (nextHandler != null) {
            nextHandler.calculation(scoreParams);
        }
    }

    /**
     * 司机服务分分值计算
     * --      (新司机?1.3:1) * (司机考核数 <= 5 ? 5:司机考评分)
     * f(x) =  ——————————————————————————————————————————————
     * --      5 * (专车 ? 1.2:1)
     *
     * @param driverScoreVo
     * @return
     */
    private Double score(DriverScoreVo driverScoreVo) {
        Double molecule = driverScoreVo.getNewDriver() == 1 ? 1.3 : 1;
        molecule *= driverScoreVo.getEvaluateTotal() <= 5 ? 5 : ParamUtil.defaultIfNull(driverScoreVo.getEvaluateAvg(), 5D);
        Double denominator = 5 * driverScoreVo.getBusinessType() == CommonConstant.BUSINESS_TYPE_SPEC ? 1.2 : 1;
        return BigDecimal.valueOf(molecule / denominator).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();

    }
}
